package com.petshop.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock {

    private static final String KEY_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true);
    //用于获取释放锁的lua脚本
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    private StringRedisTemplate redisTemplate;
    private String name;

    public SimpleRedisLock(String name, StringRedisTemplate redisTemplate) {
        this.name = name;
        this.redisTemplate = redisTemplate;
    }

    /**
     * 尝试获取锁
     *
     * @param timeoutSec 锁持有的有效期时间，到期自动释放
     * @return true代表获取成功，false代表获取失败
     */
    @Override
    public boolean tryLock(long timeoutSec) {
        //获取线程标识
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        //获取锁
        Boolean isOk = redisTemplate.opsForValue()
                .setIfAbsent(KEY_PREFIX + name, threadId, timeoutSec, TimeUnit.SECONDS);
        //如果isOK是null，那么拆箱就会出现空指针问题，所以用这种方式返回。
        return Boolean.TRUE.equals(isOk);
    }

    /**
     * 释放锁
     */
    //基于Lua脚本
    public void unlock() {
        //实现了判断锁标识和释放锁两个动作的原子性
        redisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + name),
                ID_PREFIX + Thread.currentThread().getId());
    }

//    @Override
//    public void unlock() {
//        //获取线程标识
//        String threadId = ID_PREFIX+Thread.currentThread().getId();
//        //获取锁中的标识
//        String id = redisTemplate.opsForValue().get(KEY_PREFIX + name);
//        //锁标识和线程标识一致才可以释放锁
//        if(threadId.equals(id)) {
//            //释放锁
//            redisTemplate.delete(KEY_PREFIX+name);
//        }
//    }
}
